package com.caiheng.api.service.estate.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.asymmetric.AsymmetricManager;
import com.alipay.api.internal.util.asymmetric.IAsymmetricEncryptor;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.dao.estate.EstateMapper;
import com.caiheng.api.dao.estate.EstateVisitRecordMapper;
import com.caiheng.api.dao.estate.PropertyMapper;
import com.caiheng.api.entity.dto.VisitorInfoDto;
import com.caiheng.api.entity.estate.Estate;
import com.caiheng.api.entity.estate.EstateVisitRecord;
import com.caiheng.api.entity.estate.Property;
import com.caiheng.api.exception.TransactionalException;
import com.caiheng.api.service.base.impl.BaseServiceImpl;
import com.caiheng.api.service.estate.EstateVisitRecordService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * 支付宝门禁登记记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-25
 */
@Service
public class EstateVisitRecordServiceImpl extends BaseServiceImpl<EstateVisitRecordMapper, EstateVisitRecord> implements EstateVisitRecordService {

    @Resource
    private EstateVisitRecordMapper estateVisitRecordMapper;
    @Resource
    private EstateMapper estateMapper;
    @Resource
    private PropertyMapper propertyMapper;

    @Value("${web.spiPublicKey}")
    private String spiPublicKey;//

    @Value("${web.spiPrivateKey}")
    private String spiPrivateKey;//



    @Override
    @Transactional
    public int addRecord(String formData, String visitorInfo, String bizContentJson, String utc_timestamp) {
        int ret = 0;
        try{

            EstateVisitRecord visitRecord = new EstateVisitRecord();

            JSONObject form = JSONUtil.parseObj(formData);
            if(form != null && form.size() > 0){
                visitRecord.setFormData(formData);
            }

            JSONObject bizContent = JSONUtil.parseObj(bizContentJson);
            String groupName  = bizContent.getStr("groupName");
            visitRecord.setVisitId(bizContent.getStr("visitId"));
            visitRecord.setSceneCode(bizContent.getStr("sceneCode"));
            visitRecord.setSceneName(bizContent.getStr("sceneName"));
            visitRecord.setVisitType(bizContent.getStr("visitType"));
            visitRecord.setEstateName(groupName);

            QueryWrapper<Estate> qwEstate = new QueryWrapper<>();
            qwEstate.eq("estate_name", groupName);
            qwEstate.last("limit 1");
            Estate estate = estateMapper.selectOne(qwEstate);
            if(estate!=null){
                visitRecord.setEstateId(estate.getId());
                visitRecord.setPropertyId(estate.getPropertyId());
                Property property = propertyMapper.selectById(estate.getPropertyId());
                visitRecord.setPropertyName(property.getPropertyName());
            }


            if (StrUtil.isNotBlank(visitorInfo)) {
                VisitorInfoDto visitorInfoDto = JSONUtil.toBean(visitorInfo, VisitorInfoDto.class);
                //VisitorInfoDto(extInfo=null, userId=2088822985321631, nickName=临时访客, certType=, certNo=, mobile=13849624999, realName=null)
                visitRecord.setNickName(visitorInfoDto.getNickName());
                visitRecord.setMobile(visitorInfoDto.getMobile());
                visitRecord.setRealName(visitorInfoDto.getRealName());
                visitRecord.setCertType(visitorInfoDto.getCertType());
                visitRecord.setCertNo(visitorInfoDto.getCertNo());
                visitRecord.setExtInfo(visitorInfoDto.getExtInfo());
            }

            if(StrUtil.isNotBlank(utc_timestamp)){
                visitRecord.setVisitTime(new Date(Long.parseLong(utc_timestamp)));
            }

            QueryWrapper<EstateVisitRecord> qwRecord = new QueryWrapper<>();
            qwRecord.eq("visit_id", visitRecord.getVisitId());
            long count = estateVisitRecordMapper.selectCount(qwRecord);
            if(count == 0){
                ret = estateVisitRecordMapper.insert(visitRecord);
                if(ret <= 0){
                    throw new TransactionalException("estateVisitRecordMapper insert error");
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            throw new TransactionalException("EstateVisitRecordServiceImpl system error");
        }
        return ret;
    }



    /**
     * 初始密码器
     *
     * @return
     */
    IAsymmetricEncryptor encryptor() {
        try {
            return AsymmetricManager.getByName("RSA2");
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }
}
